package yxy.game.pm2.active.module;

import org.joda.time.DateTime;
import yxy.apple.util.redisson.RedisException;
import yxy.cherry.data.DataCenter;
import yxy.cherry.data.bean.actsevenday;
import yxy.cherry.data.bean.actsevendayreward;
import yxy.game.pm2.active.ActiveUtil;
import yxy.game.pm2.active.module.actdata.ActDataCenter;
import yxy.game.pm2.active.module.subordinateclass.sdtask;
import yxy.game.pm2.bean.PlayerBean;
import yxy.game.pm2.bean.db.dao.MySQLCacheDAO;
import yxy.game.pm2.bean.module.PlayerModule;
import yxy.game.pm2.bean.task.Task;
import yxy.game.pm2.bean.task.TaskType;
import yxy.game.pm2.module.task.TaskHandle;
import yxy.game.pm2.module.tip.TipHandle;
import yxy.game.pm2.module.tip.TipType;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * 七日目标 14天一轮 1-7 开启
 * @author Dell
 *
 */
public class ActiveModule_七日目标 extends PlayerModule {

	private static int acttype = 111;	//活动类型
	
	//bean ------------------------------------------------
	private DateTime playercreate;	//玩家创建时间
	private int round;		//轮次
	private int runday;		//运行天数
	private DateTime end;	//本轮结束时间
	private int payamount;	//充值金额
	private int finishnum;		//完成任务数 领取完奖励才增加
	private ArrayList<Integer> getboxids = new ArrayList<Integer>();	//领取的宝箱id
	private ArrayList<Integer> buyids = new ArrayList<Integer>();		//购买的福利礼包list
	private HashMap<String, sdtask> codetaskmap = new HashMap<String, sdtask>();// 所有任务

	public DateTime getPlayercreate() {
		return playercreate;
	}
	public void setPlayercreate(DateTime playercreate) {
		this.playercreate = playercreate;
	}
	public int getRound() {
		return round;
	}
	public void setRound(int round) {
		this.round = round;
	}
	public int getRunday() {
		return runday;
	}
	public void setRunday(int runday) {
		this.runday = runday;
	}
	public DateTime getEnd() {
		return end;
	}
	public void setEnd(DateTime end) {
		this.end = end;
	}
	public int getPayamount() {
		return payamount;
	}
	public void setPayamount(int payamount) {
		this.payamount = payamount;
	}
	public int getFinishnum() {
		return finishnum;
	}
	public void setFinishnum(int finishnum) {
		this.finishnum = finishnum;
	}
	public ArrayList<Integer> getGetboxids() {
		return getboxids;
	}
	public void setGetboxids(ArrayList<Integer> getboxids) {
		this.getboxids = getboxids;
	}
	public ArrayList<Integer> getBuyids() {
		return buyids;
	}
	public void setBuyids(ArrayList<Integer> buyids) {
		this.buyids = buyids;
	}
	public HashMap<String, sdtask> getCodetaskmap() {
		return codetaskmap;
	}
	public void setCodetaskmap(HashMap<String, sdtask> codetaskmap) {
		this.codetaskmap = codetaskmap;
	}

	//func ------------------------------------------------
	
//	public static final int canget = 1;
//	public static final int hadget = 2;
//	public static final int cannotget = 3;
	
//	类型，宝箱（2）还是任务（1）
	public static final int task = 1;
	public static final int box = 2;

	/**
	 * 初始化
	 * @param playerCode
	 * @return
	 */
	private static ActiveModule_七日目标 create(String playerCode) {
		ActiveModule_七日目标 am = new ActiveModule_七日目标();
		am.setRound(1);
		
		PlayerBean pb = PlayerBean.get(playerCode);
		am.setPlayerCode(playerCode);
		am.setPlayercreate(pb.getCreateTime());
		
		int runday = am.getrunday();
		am.setRunday(runday);
		
		DateTime end = am.getrunendtime(runday);
		am.setEnd(end);
		
		am.setFinishnum(0);
		am.setPayamount(0);

		//活动开启状态 初始化任务
		if(runday >= 1 && runday <= 7) {
			Map<String, actsevenday> asdmap = ActDataCenter.getAllData(actsevenday.class, playerCode);
			for(actsevenday data : asdmap.values()) {
				if(data.getFinish() == -1) {
					continue;
				}
				
				int taskid = data.getTaskid1();
				yxy.cherry.data.bean.task taskdata = DataCenter.getData(taskid, yxy.cherry.data.bean.task.class);
				Task taskbean = Task.create(playerCode, taskdata, data.getId());
				
				sdtask sd = new sdtask();
				sd.setId(data.getId());
				sd.setTaskid(taskid);
				sd.setCode(taskbean.getCode());
				sd.setGroup(data.getGroup());
				
				am.getCodetaskmap().put(taskbean.getCode(), sd);
			}
	
		}
		
		am.set();
		
		TaskHandle.handle(playerCode, TaskType.统计型_七日目标活动登陆_次数, 1);
		return am;
	}
	
	/**
	 * 活动更新
	 */
	private void update() {
		int runday = getrunday();
		int round = getround();
		
		if(getPlayercreate() == null) {
			PlayerBean pb = PlayerBean.get(getPlayerCode());
			setPlayercreate(pb.getCreateTime());
			set();
		}
		
		//核对轮次  刷新轮次
		if(round != getRound()) {
			setRound(round);
			reset();
		}
		
		//核对运行天数
		if(runday != getRunday()) {	
			setRunday(runday);
			setEnd(getrunendtime(runday));
			set();
			
			TaskHandle.handle(getPlayerCode(), TaskType.统计型_七日目标活动登陆_次数, 1);
		}

	}
	
	//重置
	private void reset() {
		//清除上次开启任务
		Task.remove(getPlayerCode(), getCodetaskmap().keySet());
		setCodetaskmap(new HashMap<String, sdtask>() );
		
		// 重新初始化
		int runday = getrunday();
		setRunday(runday);
		
		DateTime end = getrunendtime(runday);
		setEnd(end);
		
		setFinishnum(0);
		setPayamount(0);
		setBuyids(new ArrayList<Integer>());
		setGetboxids(new ArrayList<Integer>());

		if(runday >= 1 && runday <= 7) {
			Map<String, actsevenday> asdmap = ActDataCenter.getAllData(actsevenday.class, getPlayerCode());
			for(actsevenday data : asdmap.values()) {
				if(data.getFinish() == -1) {
					continue;
				}
				
				int taskid = (getRound() == 1 ? data.getTaskid1() : data.getTaskid2());
				yxy.cherry.data.bean.task taskdata = DataCenter.getData(taskid, yxy.cherry.data.bean.task.class);
				Task taskbean = Task.create(getPlayerCode(), taskdata, data.getId());
				
				sdtask sd = new sdtask();
				sd.setId(data.getId());
				sd.setTaskid(taskid);
				sd.setCode(taskbean.getCode());
				sd.setGroup(data.getGroup());
				
				getCodetaskmap().put(taskbean.getCode(), sd);
			}
	
		}
		
		set();
		
		TaskHandle.handle(getPlayerCode(), TaskType.统计型_七日目标活动登陆_次数, 1);
	}
	
	
	/**
	 * 获取循环内运行天数		1-7 开启  8-14 关闭
	 * @param start
	 * @return	
	 */
	private int getrunday() {
		if(getPlayercreate() == null) {
			PlayerBean pb = PlayerBean.get(getPlayerCode());
			setPlayercreate(pb.getCreateTime());
			set();
		}
		
		int days = ActiveUtil.days(getPlayercreate(), DateTime.now());
		int runday = days % 14 + 1;
		return runday;
	}
	
	private int getround() {
		int days = ActiveUtil.days(getPlayercreate(), DateTime.now());
		int round = days / 14 + 1;
		return round;
	}
	
	/**
	 * 计算单个循环内活动结束时间	
	 * @param runday
	 * @return
	 */
	public static DateTime getrunendtime(int runday){
		DateTime now = DateTime.now();
		if(runday <= 7) {
			int surplusdays = 7 - runday;
			DateTime end = now.plusDays(surplusdays).withHourOfDay(23).withMinuteOfHour(59).withSecondOfMinute(59).withMillisOfSecond(0);
			return end;
		}else {
			int surplusdays = 7 - runday;
			DateTime end = now.plusDays(surplusdays).withHourOfDay(23).withMinuteOfHour(59).withSecondOfMinute(59).withMillisOfSecond(0);
			return end;
		}
	}
	
	//redis -----------------------------------------------
	
	static private String key(String playerCode) {
		return String.format("PLAYER:%s:ACTIVE:%S", playerCode, acttype);
	}

	public void set() {
		try {
			String key1 = key(getPlayerCode());
			setv(key1, this);
			check();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 获取ActiveModule_七日目标
	 * @param playerCode
	 * @return
	 */
	static public ActiveModule_七日目标 get(String playerCode, Boolean isNewPlayer) {
		try {
			ActiveModule_七日目标 module = getv(key(playerCode));
			if (module == null) {

				//新用户不需要去查数据库
				if(!isNewPlayer){
					module = MySQLCacheDAO.getV(key(playerCode), ActiveModule_七日目标.class);
					if(module != null){module.set();}//同步到redis
				}

				if (module == null) {
					module = create(playerCode);
				}
			}

			module.update();
			module.check();
			return module;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}


	/**
	 * 红点检查
	 */
	public void check() {
		//是否开启
		if(getrunday() > 7) {
			new ActOpenHandle().updateActOpen(getPlayerCode(), acttype, OpenType.关闭);
			new TipHandle().updateTip(getPlayerCode(), TipType.活动_七日目标奖励, false);
			return;
		}else {
			new ActOpenHandle().updateActOpen(getPlayerCode(), acttype, OpenType.开启);
		}
		
		//是否可领取
		Map<String, actsevendayreward> sevenrewardmap = ActDataCenter.getAllData(actsevendayreward.class, getPlayerCode());
		for (actsevendayreward sevenreward : sevenrewardmap.values()) {
			if(getFinishnum() < sevenreward.getCondition()) {
				continue;
			}
			
			if (getGetboxids().contains(sevenreward.getId())) {
				continue;
			}

			new TipHandle().updateTip(getPlayerCode(), TipType.活动_七日目标奖励, true);
			return;
		}
		
		for(sdtask sd : getCodetaskmap().values()) {
			if (getrunday() < sd.getGroup()) {
				continue;
			}

			Task task = Task.get(getPlayerCode(), sd.getCode());

			if (task != null && task.isFinish() && !task.isReward()) {
				new TipHandle().updateTip(getPlayerCode(), TipType.活动_七日目标奖励, true);
				return;
			}
		}
		
		new TipHandle().updateTip(getPlayerCode(), TipType.活动_七日目标奖励, false);
	}

	//存储到数据库的方法
	public static void saveToDB(String playerCode) {
		try {
			String key = key(playerCode);
			if (touchBucket(key).isExists()) {
				ActiveModule_七日目标 activeModule_七日目标 = getv(key(playerCode));
				MySQLCacheDAO.setV(key, activeModule_七日目标);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	//从redis移走数据的操作
	public static void removeAllFromRedis(String playerCode) {
		try {
			touchBucket(key(playerCode)).delete();
		} catch (RedisException e) {
			e.printStackTrace();
		}
	}

	//lock --------------------------------------------------------
	@Override
	public String lockKey() {
		return String.format("lock:%s", key(getPlayerCode()));
	}	

}

